package com.example.spring.framework.webmvc.filter;

import com.example.spring.framework.annotation.Security;
import com.example.spring.framework.context.ApplicationContext;
import com.example.spring.framework.util.StringUtils;
import com.example.spring.framework.webmvc.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class FilterChain {

    private final String user = "cherish";

    public void doFilter(HandlerMapping handlerMapping, HttpServletRequest req, HttpServletResponse resp) throws Exception {

        String username = req.getParameter("username");
        if (StringUtils.isEmpty(username)) {
            throw new Exception("该用户不合法");
        }


        Object obj = handlerMapping.getController();
        Method method = handlerMapping.getMethod();
        if (obj.getClass().isAnnotationPresent(Security.class) || method.isAnnotationPresent(Security.class)) {
            // 有注解的安全测试类
            if (user.equals(username)) {
                System.out.println("用户校验通过");
            } else {
                throw new Exception("用户" + username + "不合法");
            }
        }

    }

}
